<template>
    <view class="app">
        <load :ready="ready"></load>

        <view class="form">
			<!-- {{userInfo}} -->
			 <!-- <form :model="form" @submit="bindsubmit" form-type="submit" ref="uForm" :error-type="['toast']"> -->
            <form @submit="bindsubmit" form-type="submit">
				<button class="u-reset-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<u-form-item label="头像"  label-width="160">
					<view class="ibox">
							<u-image :src="temp || avatarUrl" shape="circle" width="160" height="160"></u-image>
						</view>
					</u-form-item>
				</button>
				
				<!-- 	<u-form-item label="头像"  label-width="160">
						<view class="ibox"  @click="up">
							<u-image :src="temp || avatarUrl" shape="circle" width="160" height="160"></u-image>
						</view>
					</u-form-item> -->
				
				</u-form-item>
				<u-form-item label="昵称"  prop="name" label-width="160">
					<input type="nickname" name="name" @input="onInput" v-model="form.name" placeholder="请输入">
				</u-form-item>
				
				
				<view class="btnbox fixed">
					<!-- <u-button type="primary" 	form-type="submit" @click="submit()" shape="circle" :custom-style="btnStyle">保存</u-button> -->
					<button type="primary" style="border-radius: 50px;"	form-type="submit" shape="circle" :custom-style="btnStyle">保存</button>
				</view>
            </form>
        </view>
		
		<u-gap height="160"></u-gap>
        
		
    </view>
</template>

<script>
import { mapState, mapActions, mapMutations, mapGetters } from 'vuex';
import { mixinsBase } from '@/common/js/mixins';
let that;
export default {
    mixins: [mixinsBase],
    components: {},
    data() {
        return {
            // ready: true,
			btnStyle: {
				...this.$config.btnStyle,
				width:'100%'
			},
            rules: {
                name: [
                    {
                        required: true,
                        message: '请输入姓名',
                        // 可以单个或者同时写两个触发验证方式
                        trigger: ['change', 'blur']
                    }
                ]
            },
            form: {
                agencyPortrait: '',
				name:'',
            },
			temp: '',
			avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
			user:{},
        };
    },
    onLoad() {
        that = this;
		 uni.$on('uAvatarCropper',this.uAvatarCropper);
		this.getInit();
    },
    onReady() {
        // this.$refs.uForm.setRules(this.rules);
    },
    onShow() {
    },
    onUnload() {
        that = null;
		uni.$off('uAvatarCropper',this.uAvatarCropper);
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        // this.getInit(data=>{
        //      uni.stopPullDownRefresh();
        //      common.showTip('刷新成功');
        // });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        //       return {
        // 	// path,
        // 	imageUrl:config.shareImg,
        // 	// title
        // }
    },
    methods: {
		async bindsubmit(e){
			console.log(e);
			uni.showLoading({
			    title:'提交中'
			})
			let param = {
				name: e.detail.value.name
			};
			if(this.temp.length){
			    uni.showLoading({
			        title: '上传头像中',
			        mask: false
			    });
				
			   let data  = await that.$up(this.temp, that.$config.upload);
			    // let data  = await that.$up(this.temp, 'https://medicalapi.zhilongsoft.com/app/storage/upload');
			   if(data){
				   console.log(data);
			       param.avatar = data;
			   }
			}
			console.log('param', param);
			uni.showLoading({
			    title: '上传数据中',
			    mask: false
			});
			const res = await this.$api.userInfos(param);
			uni.hideLoading();
			if (res.data.code == this.$config.RESOK) {
				let userInfo =  {
					 ...this.userInfo,
					 ...param,
				 }
			   this.setUserInfo(userInfo);
			    this.$common.showTip(res.data.msg, 'success');
			    setTimeout(()=>{
			        this.$common.goback();
			    }, this.$config.timeLoad)
			} else {
			    this.$common.showTip(res.data.msg, 'none');
			}
		},
		onInput(e){
			console.log(e);
		},
		async onChooseAvatar(e) {
			 const that = this;
			 console.log(e)
		    const { avatarUrl } = e.detail 
			console.log('avatarUrl', avatarUrl)
			this.temp= avatarUrl;
			// let data  = await that.$up(this.temp, that.$config.upload);
			//  let data  = await that.$up(this.temp, 'https://medicalapi.zhilongsoft.com/app/storage/upload');
			//  console.log('data',data);
			//  console.log(data);
			// if(data){
			//    console.log(data);
			//     param.avatar = data;
			// }
			// let formData = {
			// 	'user':'test'
			// }
			// let header ={
			// }
			// if(this.userInfo && this.userInfo.token){
			//     formData.token = this.userInfo.token;
			// 	header.token = this.userInfo.token;
			// }
			
			// uni.uploadFile({
			//     url: 'https://medicalapi.zhilongsoft.com/app/storage/upload',
			//     filePath: avatarUrl,
			//     name: 'file',
			// 	header,
			//     formData,
			//     success: (res) => {
			//         console.log(res);
			//         let resdata = JSON.parse(res.data);
			//         console.log(resdata);
			// 		if(resdata.code == 200){
			// 			console.log('--',resdata.data.url)
						
						
			// 			uni.downloadFile({
			// 				url: resdata.data.url, //仅为示例，并非真实的资源
			// 				success: (res) => {
			// 					if (res.statusCode === 200) {
			// 						console.log('下载成功 downloadFile');
			// 						console.log(res.tempFilePath)
			// 						that.temp = res.tempFilePath
			// 					}
			// 				}
			// 			});
			// 		}
			//     },
			//     fail(err){
			//         jres(err)
			//     }
			// });
			
		  },
		async uAvatarCropper(path){
		       console.log('uAvatarCropper path');
		    this.temp = path;
		 },
		async getInit(){
			let res = await this.$api.getUserList();
			if(res.data.id){
				res.data = this.$user.normalFilter(res.data)
				this.user = res.data
				this.form.name = this.user.name
				if(this.user.avatar && this.user.avatar.length){
					this.avatarUrl = this.user.avatar
				}
			}
		},
    //   async submit(){
    //       let istrue = true;
    //       this.$refs.uForm.validate(valid => {
    //           if (valid) {
    //               console.log('验证通过');
    //           } else {
    //               console.log('验证失败');
    //               istrue= false
    //           }
    //       });
    //       if(!istrue)return;
    //       uni.showLoading({
    //           title:'提交中'
    //       })
    //       let param = Object.assign({},this.form);
    //       if(this.temp.length){
    //           uni.showLoading({
    //               title: '上传头像中',
    //               mask: false
    //           });
    //          let data  = await that.$up(this.temp, that.$config.upload);
    //          if(data){
    //              param.agencyPortrait = data.url;
    //          }
    //       }
		  // console.log('param', param);
    //       uni.showLoading({
    //           title: '上传数据中',
    //           mask: false
    //       });
    //       const res = await this.$api.agencyAuthProfile(param);
    //       uni.hideLoading();
    //       if (res.data.code == this.$config.RESOK) {
    //          let userInfo =  {
				//  ...this.userInfo,
				//  ...param,
			 // }
    //          this.setUserInfo(userInfo);
    //           this.$common.showTip(res.data.msg, 'success');
    //           setTimeout(()=>{
    //               this.$common.goback();
    //           }, this.$config.timeLoad)
    //       } else {
    //           this.$common.showTip(res.data.msg, 'none');
    //       }
    //   },
		up() {
			this.$u.route({
		        // 关于此路径，请见下方"注意事项"
		        url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
		        // 内部已设置以下默认参数值，可不传这些参数
		        params: {
		            // 输出图片宽度，高等于宽，单位px
		            destWidth: 500,
		            // 裁剪框宽度，高等于宽，单位px
		            rectWidth: 280,
		            // 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
		            fileType: 'jpg',
		        }
		    })
		},
        ...mapActions(['setUserInfo'])
    },
    computed: {
        ...mapState({
            userInfo: 'userInfo'
        })
    }
};
</script>

<style scoped lang="scss">
page {
    background-color: $uni-bg-color-grey;
}

.ibox{
	width: 180rpx;
	height: 180rpx;
	position: relative;
	.icon {
	    width: 54rpx;
	    height: 54rpx;
	    position: absolute;
	    right: 0;
	    bottom: 0;
	}
}
.avathor {
    background-color: $uni-bg-color;
    padding: 30rpx 0 40rpx;
    .ibox {
       
    }
   
}
.form {
	background: #fff;
	padding: 0 30rpx;
    .form-item {
        background: $uni-bg-color;
        margin-bottom: 30rpx;
        padding: 0 40rpx;
    }
}
</style>
